package com.yunxin.download.server.infra.utils;

import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.utils.AliYunOssUtils;
import com.yunxin.download.server.infra.constant.enums.DownloadResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.context.ApplicationContext;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zero°
 * @date 2021/6/18
 */
@Slf4j
public enum AliYunOssUtil {

    /**
     * 实例
     */
    X;

    private AliYunOssUtils aliYunOssUtils;

    private String bucket;

    public void afterPropertiesSet() {
        ApplicationContext context = SpringContextUtils.getApplicationContext();
        bucket = context.getEnvironment().getProperty("aliYun.oss.bucket");
        aliYunOssUtils = new AliYunOssUtils(context.getEnvironment().getProperty("aliYun.oss.endpoint"),
                context.getEnvironment().getProperty("aliYun.oss.accessKeyId"), context.getEnvironment().getProperty("aliYun.oss.accessKeySecret"));
    }

    /**
     * 上传到oss
     * @param ossKey ossKey
     * @param inputStream inputStream
     */
    public void upload(String ossKey, InputStream inputStream) {
        afterPropertiesSet();
        //释放资源
        aliYunOssUtils.upload(bucket, ossKey, inputStream);
        aliYunOssUtils.destroy();
    }

    /**
     * 下载
     * @param ossKey ossKey
     *
     * @return InputStream InputStream
     */
    public InputStream download(String ossKey) {
        try {
            afterPropertiesSet();
            InputStream downloadInputStream = aliYunOssUtils.download(bucket, ossKey);
            //复制到另外一个流里面 否则关闭以后 无法读取流里面的数据
            return IOUtils.toBufferedInputStream(downloadInputStream);
        } catch (IOException e) {
            throw new BusinessException(DownloadResultCode.GET_TEMPLATE_FILE_ERROR);
        } finally {
            aliYunOssUtils.destroy();
        }
    }

}
